package com.qf.shop.pay.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.OrderVO;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.qf.shop.common.exception.BusinessException;
import com.qf.shop.pay.config.AliPayConfig2;
import com.qf.shop.pay.feign.api.OrderService;
import com.qf.shop.pay.vo.OrderVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/pay")
@Slf4j
public class AliPayController {

    @Autowired
    private OrderService orderService;

    @GetMapping("/ali")
    public void ali(String orderId, HttpServletRequest request, HttpServletResponse httpResponse) throws Exception {
        log.debug("orderId:{}", orderId);

        // 根据订单编号查询订单信息
        OrderVo orderVo = orderService.getOrderById(orderId);
        log.debug("orderVo:", orderVo);
        if (orderVo == null) {
            throw new BusinessException("订单不存在", 301);
        }

        // 1、获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(
                AliPayConfig2.gatewayUrl, // 支付宝的网关
                AliPayConfig2.app_id, // 应用AppId
                AliPayConfig2.merchant_private_key, // 应用私钥
                "json", // 数据格式
                AliPayConfig2.charset, // 数据的编码
                AliPayConfig2.alipay_public_key, // 阿里的公钥
                AliPayConfig2.sign_type); // 签名的类型

        // 2、跳转的地址
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AliPayConfig2.return_url); // 同步跳转地址
        alipayRequest.setNotifyUrl(AliPayConfig2.notify_url); // 异步跳转地址

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = orderId;
        //付款金额，必填
        String total_amount = orderVo.getTotalPrice().toString();
        //订单名称，必填
        String subject = "2103-电商";
        //商品描述，可空
        String body = "电商的描述"; // 商品详情中的第一个商品的名字

        String time = "3m"; // 支付宝超时时间

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"timeout_express\":\"" + time + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        String result = alipayClient.pageExecute(alipayRequest).getBody();

        log.debug("result:{}",result);
        httpResponse.setContentType("text/html;charset=" + AliPayConfig2.charset);
        httpResponse.getWriter().write(result); //直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();

    }

    /**
     * 1、延签(验证当请求是支付宝调用的)
     * 2、支付的状态
     * 3、对比订单的信息是否和支付的一致
     * 4、修改订单的状态为已支付
     */
    @PostMapping("/aliCallback")
    @ResponseBody
    public void aliCallback(HttpServletRequest request) {
        log.debug("支付宝回调了。。。");

        // 1.获取支付宝调用给你是传递的所有的参数
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (Map.Entry<String, String[]> stringEntry : parameterMap.entrySet()) {
            System.out.println(stringEntry.getKey() + ":" + Arrays.toString(stringEntry.getValue()));
            params.put(stringEntry.getKey(), stringEntry.getValue()[0]);
        }

        try {
            // 2.延签
            boolean signVerified = AlipaySignature.rsaCheckV1(
                    params,  //
                    AliPayConfig2.alipay_public_key,
                    AliPayConfig2.charset,
                    AliPayConfig2.sign_type); //调用SDK验证签名
            if (signVerified) {
                log.debug("延签通过。。。");
                String trade_status = params.get("trade_status"); // 定的支付状态
                String out_trade_no = params.get("out_trade_no"); // 订单编号
                String total_amount = params.get("total_amount"); // 订单编号
                // 3.查询订单的支付状态
                if ("TRADE_SUCCESS".equals(trade_status)) {
                    // 再次调用支付宝查询订单状态

                    // 对比支付的金额和下单的金额是否一致
//                    OrderVo orderVo = orderService.getOrderById(out_trade_no);

                    // 修改订单的状态
                    orderService.updateOrderStatus(out_trade_no, 2);
                }

            } else {
                log.error("非法调用阿里的回调函数");
            }
        } catch (AlipayApiException e) {
            log.error("延签出现异常，非法调用阿里的回调函数");
        }
    }


    @GetMapping("/weixin")
    public String weixin() {
        return "wexin";
    }
}
